package cn.bitkit.tools.data;

import cn.bitkit.base.util.StringUtil;
import cn.bitkit.tools.common.IOUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author changbo
 */
@Slf4j
public class GzipUtil {


    @SneakyThrows
    public static String gzip(String text) {
        if (StringUtil.isEmpty(text)) {
            return text;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(text.getBytes(StandardCharsets.UTF_8));
        gzip.close();
        return StringUtil.encodeBase64(out.toByteArray());
    }

    @SneakyThrows
    public static String unGzip(String text) {
        if (StringUtil.isEmpty(text)) {
            return text;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(StringUtil.decodeBase64(text));
        GZIPInputStream gzip = new GZIPInputStream(in);
        IOUtil.write(gzip, out);
        return out.toString(StandardCharsets.UTF_8);
    }

}
